package com.example.android.myapp;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MyFootprintActivity extends ListActivity {
    private static final String CATEGORY_SAMPLE_CODE = "com.example.android.myapp";
    
    private static final String KEY_TITLE            = "title";
    
    private static final String KEY_INTENT           = "intent";
    
    private static final String KEY_PREFIX           = "com.example.android.myapp.Path";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        String prefix = intent.getStringExtra(KEY_PREFIX);
        
        if (prefix == null) {
            prefix = "";
        }
        
        setListAdapter(new SimpleAdapter(this, getData(prefix), android.R.layout.simple_list_item_1,
                new String[] { KEY_TITLE }, new int[] { android.R.id.text1 }));
        getListView().setTextFilterEnabled(true);
    }
    
    protected List<Map<String, Object>> getData(String prefix) {
        List<Map<String, Object>> map_list = new ArrayList<Map<String, Object>>();
        
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(CATEGORY_SAMPLE_CODE);
        mainIntent.setPackage(getPackageName());
        
        PackageManager pm = getPackageManager();
        List<ResolveInfo> info_list = pm.queryIntentActivities(mainIntent, 0);
        
        if (null == info_list)
            return map_list;
        
        String[] prefixArray;
        
        if (prefix.equals("")) {
            prefixArray = null;
        } else {
            prefixArray = prefix.split("/");
        }
        
        Map<String, Boolean> entries = new HashMap<String, Boolean>();
        
        for (int i = 0, n = info_list.size(); i < n; i++) {
            ResolveInfo info = info_list.get(i);
            CharSequence labelSeq = info.loadLabel(pm);
            String label = labelSeq != null ? labelSeq.toString() : info.activityInfo.name;
            
            if (prefix.length() == 0 || label.startsWith(prefix)) {
                String[] labelArray = label.split("/");
                String nextLabel = prefixArray == null ? labelArray[0] : labelArray[prefixArray.length];
                
                if ((prefixArray != null ? prefixArray.length : 0) == labelArray.length - 1) {
                    addItem(map_list, nextLabel, createIntent(info.activityInfo.applicationInfo.packageName, info.activityInfo.name));
                } else {
                    if (entries.get(nextLabel) == null) {
                        addItem(map_list, nextLabel, browseIntent(prefix.equals("") ? nextLabel : prefix + "/" + nextLabel));
                        entries.put(nextLabel, true);
                    }
                }
            }
        }
        
        Collections.sort(map_list, sDisplayNameComparator);
        return map_list;
    }
    
    /**
     * The comparator that used to sort demo Activity list by Activity's label name.
     */
    private final static Comparator<Map<String, Object>> sDisplayNameComparator = new Comparator<Map<String, Object>>() {
        private final Collator collator = Collator.getInstance();
        
        @Override
        public int compare(Map<String, Object> map1, Map<String, Object> map2) {
            return collator.compare(map1.get(KEY_TITLE), map2.get(KEY_TITLE));
        }
    };
    
    protected Intent createIntent(String packagename, String classname) {
        return new Intent().setClassName(packagename, classname);
    }
    
    protected Intent browseIntent(String path) {
        Intent result = new Intent();
        result.setClass(this, MyFootprintActivity.class);
        result.putExtra(KEY_PREFIX, path);
        return result;
    }
    
    protected void addItem(List<Map<String, Object>> list, String name, Intent intent) {
        Map<String, Object> temp = new HashMap<String, Object>();
        temp.put(KEY_TITLE, name);
        temp.put(KEY_INTENT, intent);
        list.add(temp);
    }
    
    @Override
    @SuppressWarnings("unchecked")
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Map<String, Object> map = (Map<String, Object>) l.getItemAtPosition(position);
        
        Intent intent = (Intent) map.get(KEY_INTENT);
        startActivity(intent);
    }
}